export type Sidebar = {
  id?: number;
  parentId?: number;
  order?: number;
  name?: string;
  icon?: string;
  link?: string;
  children?: Sidebar[];
  createdAt?: string;
}

const fakeSidebar = {
  records: {} as Record<string, Sidebar>,

  async create(values: Sidebar): Promise<Sidebar> {
    const id = values.id || Math.floor(Math.random() * 1000000);
    if (values.children && values.children.length > 0) {
      values.children = await Promise.all(values.children.map((child) => {
        return this.create({ ...child, parentId: id });
      }));
    }

    const createdAt = new Date().toISOString();
    const record = { ...values, id, createdAt };
    if (values.parentId) {
      return record;
    }
    this.records[id] = record;
    return this.records[id];
  },

  async getAll(): Promise<Sidebar[]> {
    return Object.keys(this.records).map((id) => this.records[id]).sort((a, b) => (a.order ?? 0) - (b.order ?? 0));
  }
};

export async function getAllSidebar() {
  await new Promise((resolve) => setTimeout(resolve, 200));
  return fakeSidebar.getAll();
}

[
  {
    name: "Home",
    order: 1,
    icon: "m2.25 12 8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25",
    link: "/admin",
  },
  {
    name: "Roles & Permissions",
    order: 2,
    icon: "M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0v3.75m-.75 11.25h10.5a2.25 2.25 0 0 0 2.25-2.25v-6.75a2.25 2.25 0 0 0-2.25-2.25H6.75a2.25 2.25 0 0 0-2.25 2.25v6.75a2.25 2.25 0 0 0 2.25 2.25Z",
    children: [
      {
        name: "Roles",
        link: "/admin/roles",
      },
      {
        name: "Permissions",
        link: "/admin/permissions",
      },
    ],
  },
  {
    name: "Parent",
    order: 3,
    icon: "m2.25 12 8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75M8.25 21h8.25",
    children: [
      {
        name: "Submenu 1",
        link: "/admin/submenu1",
      },
      {
        name: "Submenu 2",
        link: "/admin/submenu2",
      },
      {
        name: "Parent",
        link: "/admin/parent",
        children: [
          {
            name: "Submenu 1",
            link: "/admin/submenu1",
          },
          {
            name: "Submenu 2",
            link: "/admin/submenu2",
          },
        ],
      },
    ],
  }
].forEach((sidebar) => {
  fakeSidebar.create({
    ...sidebar
  });
});